package minesweep.entity;

import org.json.JSONObject;

import java.util.Collection;
import java.util.Map;

/**
 * Created by fuatnow on 17/1/19.
 */
public class JsonMessage
{
    private JSONObject _rootObj;
    private JSONObject _dataObj;
    private JSONObject _errObj;
    public static final String ERROR_CODE_KEY  = "errCode";
    public static final String ERROR_MSG_KEY = "errMsg";
    public static final String CMD_ID_KEY = "cmdID";
    public JsonMessage()
    {
        _rootObj = new JSONObject();
        _dataObj = new JSONObject();
        _errObj = new JSONObject();
        _rootObj.put("data",_dataObj);
        _rootObj.put("errInfo",_errObj);
    }

    public JsonMessage(int cmdId)
    {
        _rootObj = new JSONObject();
        _dataObj = new JSONObject();
        _errObj = new JSONObject();
        _rootObj.put(CMD_ID_KEY,cmdId);
        _rootObj.put("data",_dataObj);
        _rootObj.put("errInfo",_errObj);
    }

    public String toString()
    {
        return _rootObj.toString();
    }

    private JSONObject getUseJsonObj(String key)
    {
        JSONObject obj = _dataObj;
        switch (key)
        {
            case ERROR_CODE_KEY:
            case ERROR_MSG_KEY:
                obj = _errObj;
                break;
            case CMD_ID_KEY:
                obj = _rootObj;
                break;
            default:
                break;
        }
        return obj;
    }

    public JSONObject put(String key,boolean value)
    {
        return this.getUseJsonObj(key).put(key,value);
    }

    public  JSONObject put(String key, Collection<Object> value)
    {
        return this.getUseJsonObj(key).put(key,value);
    }

    public  JSONObject put(String key , double value)
    {
        return this.getUseJsonObj(key).put(key,value);
    }

    public  JSONObject put(String key, int value)
    {
        return this.getUseJsonObj(key).put(key,value);
    }

    public  JSONObject put(String key, long value)
    {
        return this.getUseJsonObj(key).put(key,value);
    }

    public  JSONObject put(String key, Map<String,Object> value)
    {
        return this.getUseJsonObj(key).put(key,value);
    }

    public  JSONObject put(String key, Object value)
    {
        return this.getUseJsonObj(key).put(key,value);
    }

    public JSONObject getRootObj() {
        return _rootObj;
    }

    public JSONObject getDataObj() {
        return _dataObj;
    }

    public JSONObject getErrObj() {
        return _errObj;
    }
}
